import config from '@/request/baseUrl.js';
import {
	webSrc,
	compareVersion
} from '@/common/mothed.js';
import {
	getAppVersion
} from "@/request/user.js";

// 上传图片 /common/upload
export const commonUpload = async (filePath, url = '/common/watermarkUpload', name = 'file') => {
	const token = uni.getStorageSync('TOKEN')
	let position = ""; // 定位信息
	// #ifdef APP-PLUS
	position = await getLocation()
	// #endif
	// #ifdef H5
	position = `H5不支持定位信息，仅供样式参考`;
	// #endif
	return new Promise((resolve) => {
		console.log('上传图片', position)
		uni.uploadFile({
			url: config.baseUrl + url,
			filePath: filePath,
			formData: {
				position,
			},
			header: {
				Authorization: "Bearer " + token
			},
			name: name,
			success: data => {
				let info = JSON.parse(data.data)
				resolve(info);
			},
			fail: () => {
				reject();
				uni.showToast({
					title: '上传失败',
					icon: 'none',
					duration: 2000
				})
			}
		});
	})
}

const getLocation = () => {
	return new Promise((resolve) => {
		uni.getLocation({
			type: "gcj02",
			geocode: true,
			success: (res) => {
				if (res.address) {
					const {
						province,
						city,
						district,
						street,
						streetNum
					} = res.address;
					resolve(`${province}${city}${district}${street}${streetNum}`);
				}
			},
			fail: () => {
				resolve("定位失败");
			},
		});
	});
};

// 检测版本更新
export const uploadApp = (loading = false) => {
	if (loading) {
		uni.showLoading({
			title: "检查更新中...",
			icon: "none",
		});
	}
	let data = {
		// #ifdef APP-PLUS
		type: plus.os.name == "Android" ? "ANDROID" : "IOS",
		// #endif
		// #ifndef APP-PLUS
		type: "ANDROID",
		// #endif
		clientType: 2, // 客户端类型（1维保 2业主 3维修）
	}
	getAppVersion(data).then((res) => {
		if (res.code == 200) {
			let info = res.data;
			if (info) {
				// #ifdef APP-PLUS
				plus.runtime
					.getProperty(plus.runtime.appid, (app) => {
						setTimeout(() => {
							if (parseInt(info.version) > parseInt(app.versionCode)) {
								uni.hideLoading();
								uni.$emit("upgrade", info);
							} else {
								if (loading) {
									uni.hideLoading();
									uni.showToast({
										title: "已是最新版本",
										icon: "none",
									});
								}
							}
						}, 1000);
					});
				// #endif
				// #ifndef APP-PLUS
				uni.getSystemInfo().then((res) => {
					setTimeout(() => {
						if (parseInt(info.version) > parseInt(res.appVersionCode)) {
							uni.hideLoading();
							uni.$emit("upgrade", info);
						} else {
							if (loading) {
								uni.hideLoading();
								uni.showToast({
									title: "已是最新版本",
									icon: "none",
								});
							}
						}
					}, 1000);
				});
				// #endif
			}
		}
	});
}

// 创建目录
export const createDirectory = (directoryPath, successCallback, failCallback) => {
	plus.io.resolveLocalFileSystemURL(directoryPath, (entry) => {
		// 如果目录已存在
		successCallback('目录已存在：' + entry.fullPath);
	}, (err) => {
		// 如果目录不存在，尝试创建
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
			fs.root.getDirectory(directoryPath, {
				create: true
			}, (newEntry) => {
				successCallback('目录创建成功：' + newEntry.fullPath);
			}, (error) => {
				failCallback('创建目录失败：' + error.message);
			});
		}, (error) => {
			failCallback('请求文件系统失败：' + error.message);
		});
	});
}